package com.yl.common.utils

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.yl.common.WebContext
import com.yl.common.getContext
import java.util.*
import kotlin.collections.HashMap


/**
 * 校验token.并且得到内容
 */
fun checkTokenAndGetValue(token: String, key: String): WebContext {
	val tokenDecode = JWT.decode(token)
	JWT.require(Algorithm.HMAC256(key)).build().verify(token)

	val value = tokenDecode.claims["data"]!!.toString()
	//将string 转成webContext
	return jacksonObjectMapper().readValue(value, WebContext::class.java)
}


/**
 * 生成token
 */
fun generateToken(expiresTime: Long, key: String): String {
	val context = getContext()
	val tokenValue = HashMap<String, Any>()
	tokenValue["userId"] = context.userId
	tokenValue["companyId"] = context.companyId
	tokenValue["subCompanyId"] = context.subCompanyId
	tokenValue["userType"] = context.userType.ordinal

	return JWT.create()
		.withClaim("data", tokenValue)
		.withExpiresAt(Date(System.currentTimeMillis() + expiresTime))
		.sign(Algorithm.HMAC256(key))
}

